package com.xiaoge.system.controller;

import com.xiaoge.auth.security.UserInfo;
import com.xiaoge.system.entity.Department;
import com.xiaoge.system.entity.Menu;
import com.xiaoge.system.entity.User;
import com.xiaoge.system.service.DepartmentService;
import com.xiaoge.system.service.MenuService;
import com.xiaoge.system.vo.LoginFrom;
import com.xiaoge.response.Result;
import com.xiaoge.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 登录
 *
 * @author zhoubin
 * @since 1.0.0
 */
@Api(tags = "LoginController")
@RestController
//允许跨域
@CrossOrigin
@ResponseBody
public class LoginController {

    private UserService userService;

    @Autowired
    private MenuService menuService;
    @Autowired
    private DepartmentService departmentService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 登录之后返回token
     *
     * @param loginFrom
     * @param request
     * @return
     */
    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public Result login(@RequestBody LoginFrom loginFrom, HttpServletRequest request) {
        return userService.login(loginFrom.getUsername(), loginFrom.getPassword(), loginFrom.getVerifyCode(), request);
    }

    /**
     * 获取当前登录用户的信息
     *
     * @param principal
     * @return
     */
    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/login/info")
    public Result getAdminInfo(Principal principal) {
        //Principal security的全局登陆用户
        if (null == principal) {
            return null;
        }
        String username = principal.getName();
        User user = userService.getAdminByUserName(username);
        user.setPassword(null);
        UserInfo userInfo = new UserInfo(user);
        List<Menu> menus=menuService.getMenusByAdminId();
        Department department=departmentService.findDeptById(user.getDepartmentId());
        Set<String>urls = new HashSet<>();
        for (Menu menu : menus) {
            if (menu.getType().equals("1")&& !ObjectUtils.isEmpty(menu.getUrl())){
                urls.add(menu.getUrl());
            }
        }
        userInfo.setUrl(urls);
        userInfo.setDeptName(department.getName());
        userInfo.setRoles(userService.getRoles(user.getId()));
        return Result.ok().message("登陆用户信息").data("user", userInfo);
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok().message("注销成功！");
    }
}